import json
import time

import redis
from django.http import HttpResponse
from ruamel import yaml

import UICaseRunner
import UITestCase
from UICaseRunner import runner
from UICaseRunner.models import CaseRunnerTask
from UITestCase.models import UIScenariosElements, UIScenarios, UIElement

# Create your views here.
from UITestProj.settings import BASE_DIR

running_case = []


def run_scenarios(request):
    if request.method == 'POST':  # 当提交表单时
        params = json.loads(request.body)
        if len(params) > 0:
            json_result = json.loads(request.body)
            scenarios_id = json_result.get('scenariosID')
            running_case = []

            scenarios_name = UIScenarios.objects.filter(id=scenarios_id).values("scenarios_name")[0]["scenarios_name"]

            cases = UIScenariosElements.objects.filter(scenarios_id=scenarios_id).values("sort_id", "id", "system_id", "scenarios_id", "model_id", "page_id", "element_id", "operator", "params").order_by("sort_id")
            cases_list = list(cases)
            for case in cases_list:
                if case["operator"] == "Insert_Scenarios":
                    scenarios_id = UIScenarios.objects.filter(id=case["params"]).values("id")[0]["id"]
                    insert_cases = UIScenariosElements.objects.filter(scenarios_id=scenarios_id).values("sort_id", "id", "system_id", "scenarios_id", "model_id", "page_id", "element_id", "operator", "params").order_by("sort_id")
                    insert_cases_list = list(insert_cases)
                    for insert_case in insert_cases_list:
                        running_case.append(insert_case)
                else:
                    running_case.append(case)

            for i in range(0, len(running_case)):
                element_id = running_case[i]["element_id"]
                if element_id != "":
                    element_detail = UIElement.objects.filter(id=int(element_id)).values("element_name", "find_type", "find_param", "another_find_type", "another_find_param")
                    element_detail_dic = list(element_detail)[0]
                    running_case[i]["element_name"] = element_detail_dic["element_name"]
                    running_case[i]["find_type"] = element_detail_dic["find_type"]
                    running_case[i]["find_param"] = element_detail_dic["find_param"]
                    running_case[i]["another_find_type"] = element_detail_dic["another_find_type"]
                    running_case[i]["another_find_param"] = element_detail_dic["another_find_param"]
                    print("")
            redis_connection = redis.Redis(host="127.0.0.1", port=6379, password=None, db=0, decode_responses=True)

            task_creater = UICaseRunner.models.CaseRunnerTask.objects.create(
                task_name=scenarios_name,
                create_by="Tester",
                create_time=UITestCase.models.timezone.now(),
                update_time=UITestCase.models.timezone.now()
            )

            cases_list_name = task_creater.task_name + "-" + str(task_creater.task_id)

            for case in running_case:
                redis_connection.rpush(cases_list_name, json.dumps(case))
            redis_connection.connection_pool.disconnect()
            redis_connection.set("cases_list_name", cases_list_name)
            redis_connection.dbsize()

            try:
                redis_connection = redis.Redis(host="127.0.0.1", port=6379, password=None, db=0, decode_responses=True)

                len_cases = redis_connection.llen(redis_connection.get("cases_list_name"))
                cases_list_name = redis_connection.get("cases_list_name")
            except Exception as e:
                print(e)
                return
            else:
                cases_list = []
                for i in range(0, len_cases):
                    cases_list.append(json.loads(redis_connection.lpop(cases_list_name)))

                print(cases_list)

                with open(BASE_DIR + '/UICaseRunner/test_cases.yaml', "w", encoding="utf-8") as f:
                    yaml.dump(cases_list, f, encoding="utf-8", allow_unicode=True, Dumper=yaml.RoundTripDumper)

            try:
                runner.beautiful_report_run()
            except Exception as e:
                print(e.__str__())
            else:
                print("")
            finally:
                time.sleep(10)
                redis_connection.delete(cases_list_name)
                print("")

            return HttpResponse('Run over. Please check report :/UITestProj/UICaseRunner/beautiful_filename.html', content_type="application/json,charset=utf-8")
        else:
            return HttpResponse('Unknown business scenarios。', content_type="application/json,charset=utf-8")
    else:
        return HttpResponse('方法错误')
